import { _decorator, log, Node, UITransform } from 'cc';
import DataManager from '../../Global/DataManager';
import { IActor, InputTypeEnum, toFixed } from '../../Common';
import { EntityManager } from '../../Base/EntityManager';
import { EntityStateEnum, EventEnum } from '../../Enum';
import { WeaponStateMachine } from './WeaponStateMachine';
import EventManager from '../../Global/EventManager';
const { ccclass, property } = _decorator;

@ccclass('WeaponMgr')
export class WeaponMgr extends EntityManager {
    private owner:number = 0;
    private body:Node = null;
    private anchor:Node = null;
    private point:Node = null;

    init(data:IActor) {
        this.owner = data.id;
        this.body = this.node.getChildByName('Body');
        this.anchor = this.body.getChildByName('Anchor');
        this.point = this.anchor.getChildByName('Point');

        this.fsm = this.body.addComponent(WeaponStateMachine);
        this.fsm.init(data.weaponType);

        this.state = EntityStateEnum.Idle;

        EventManager.Instance.on(EventEnum.BulletBorn,this.handleBulletBorn,this);
        EventManager.Instance.on(EventEnum.WeaponShoot,this.handleWeaponShoot,this);
    }
    protected onDestroy(): void {
        EventManager.Instance.off(EventEnum.WeaponShoot,this.handleWeaponShoot,this);
        EventManager.Instance.off(EventEnum.BulletBorn,this.handleBulletBorn,this);
    }

    handleBulletBorn(owner:number) {
        if(owner !== this.owner) return;
        this.state = EntityStateEnum.Attack;
        log('weapon attack')
    }

    handleWeaponShoot(){
        if(this.owner!== DataManager.Instance.myPlayerId) return;
        
        const pointWorldPos = this.point.getWorldPosition();
        const pointStagePos = DataManager.Instance.stage.getComponent(UITransform).convertToNodeSpaceAR(pointWorldPos);
        
        const anchorWorldPos = this.anchor.getWorldPosition();
        const direction = pointWorldPos.subtract(anchorWorldPos).normalize();

        EventManager.Instance.emit(EventEnum.ClientSync,{
            type:InputTypeEnum.WeaponShoot,
            owner:this.owner,
            direction:{
                x:toFixed(direction.x),
                y:toFixed(direction.y),
            },
            position:{
                x:toFixed(pointStagePos.x),
                y:toFixed(pointStagePos.y)
            }
        })
    }
}


